<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <span>设备编号：</span>
        <el-input
          v-model="query.testNo"
          placeholder="请输入设备编号"
          class="handle-input mr10"
        ></el-input>
        <el-button type="default" @click="reset">重置</el-button>
        <el-button type="primary" :icon="Search" @click="handleSearch"
          >搜索</el-button
        >
      </div>
      <el-table
        :height="tableHeight"
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column width="100" align="center" label="序号" fixed>
          <template v-slot="scope">
            {{ indexMethod(scope.$index, query.pageIndex, query.pageSize) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="deviceNo"
          label="设备编号"
          align="center"
          width="200"
        ></el-table-column>
        <el-table-column
          prop="deviceNo"
          label="出厂日期"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="productionBatch"
          label="生产批次"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="assetOwnership"
          label="资产归属"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="deviceStatus"
          width="100"
          align="center"
          label="设备状态"
        >
          <template v-slot="{ row }">
            {{ ["在线", "离线"][row.deviceStatus] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="heartbeatTime"
          label="心跳更新时间"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="creatTime"
          label="终端设备激活时间"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="offLineTime"
          label="离线时间"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="deviceSouce"
          width="100"
          align="center"
          label="设备来源"
        >
          <template v-slot="{ row }">
            {{ ["TCP长链接激活", "excel导入"][row.deviceSouce] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="importTime"
          label="excel导入时间"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template #default="scope">
            <el-button text :icon="View" @click="getTcpChart(scope.row)">
              查看折线图
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog :title="getTitle(visibleType)" v-model="editVisible" width="30%">
      <el-form label-width="70px">
        <el-form-item label="设备编号">
          <el-input
            v-model="form.deviceNo"
            :disabled="visibleType === 'watch'"
          ></el-input>
        </el-form-item>
        <el-form-item label="电表号">
          <el-input
            v-model="form.electricNo"
            :disabled="visibleType === 'watch'"
          ></el-input>
        </el-form-item>
        <el-form-item label="通道">
          <el-input
            v-model="form.passNo"
            :disabled="visibleType === 'watch'"
          ></el-input>
        </el-form-item>
        <el-form-item label="实验编号">
          <el-input
            v-model="form.testNo"
            :disabled="visibleType === 'watch'"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer v-if="visibleType !== 'watch'">
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="tcp数据列表" v-model="listVisible" width="80%">
      <div class="handle-box">
        <span>设备编号ID：</span>
        <el-input
          v-model="queryTcp.deviceNo"
          placeholder="请输入设备编号"
          class="handle-input mr10"
        ></el-input>
        <!-- <span>通道：</span>
				  <el-select v-model="queryTcp.passNo" placeholder="请选择" class="handle-input mr10">
                    <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                  </el-select> -->
        <span>时间范围：</span>
        <el-date-picker
          v-model="queryTcp.time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
        <el-button
          type="default"
          @click="Tpcreset"
          style="margin-left: 10px; margin-bottom: 7px"
          >重置</el-button
        >
        <el-button
          type="primary"
          style="margin-bottom: 7px"
          :icon="Search"
          @click="getTcp"
          >搜索</el-button
        >
      </div>
      <el-table
        :data="TcpData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column width="100" align="center" label="序号" fixed>
          <template v-slot="scope">
            {{ indexMethod(scope.$index, query.pageIndex, query.pageSize) }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="commCountIndex" label="通信计数索引" align="center" width="200"></el-table-column> -->
        <el-table-column
          prop="id"
          label="测量序号"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="deviceNo"
          label="设备编号ID"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="measurementStartTime"
          label="开始时间"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="measurementEndTime"
          label="结束时间"
          align="center"
          width="160"
        ></el-table-column>
        <!-- <el-table-column prop="oneChannelAccumulatedPower" label="A相累计电量" align="center" width="160"></el-table-column> -->
        <el-table-column
          prop="oneChannelMinutePower"
          label="A相电能"
          align="center"
          width="160"
        ></el-table-column>
        <!-- <el-table-column prop="twoChannelAccumulatedPower" label="B相累计电量" align="center" width="160"></el-table-column> -->
        <el-table-column
          prop="twoChannelMinutePower"
          label="B相电能"
          align="center"
          width="160"
        ></el-table-column>
        <!-- <el-table-column prop="threeChannelAccumulatedPower" label="三通道累计电量" align="center" width="160"></el-table-column> -->
        <el-table-column
          prop="threeChannelMinutePower"
          label="C相电能"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="minutePowerTotal"
          label="合计电能"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="accumulatedPowerTotal"
          label="累计电能"
          align="center"
          width="160"
        ></el-table-column>
      </el-table>
      <el-pagination
        small
        layout="prev, pager, next"
        @current-change="changeTpcList"
        :total="queryTcp.total"
      >
      </el-pagination>
    </el-dialog>
    <el-dialog title="tcp折线图" v-model="chartVisible" width="1400px">
      <span>通道：</span>
      <el-select
        v-model="queryCharts.passNo"
        placeholder="请选择"
        class="handle-input mr10"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <span>时间范围：</span>
      <el-date-picker
        v-model="queryCharts.time"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      >
      </el-date-picker>
      <el-button
        type="default"
        @click="chartReset"
        style="margin-left: 10px; margin-bottom: 7px"
        >重置</el-button
      >
      <el-button
        type="primary"
        style="margin-bottom: 7px"
        :icon="Search"
        @click="getTcpChart"
        >搜索</el-button
      >
      <div
        v-if="!tipBoolen"
        style="
          font-size: 20px;
          min-height: 400px;
          display: flex;
          align-items: center;
          justify-content: center;
        "
      >
        暂无数据
      </div>
      <div
        v-show="tipBoolen"
        style="width: 1200px; height: 400px; border: none"
        class="container"
        id="chartId"
        ref="myChart"
      ></div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { View, Search, Delete, Edit, Plus } from "@element-plus/icons-vue";
import {
  getOnlneList,
  getDevice,
  createDevice,
  deleteDevice,
  editDevice,
  TcpList,
  TcpChart,
} from "../../../api/index";
import { indexMethod, getViewPortHeight } from "../../../utils/tools";
import { initChart } from "./CreateEchar";
const myChart = ref(null);
const tableHeight = getViewPortHeight() - 320;
interface TableItem {
  id: number;
  name: string;
  money: string;
  state: string;
  date: string;
  address: string;
}

const getTitle = (key: string) => {
  switch (key) {
    case "edit":
      return "编辑";
    case "add":
      return "新增";
    case "watch":
      return "详情";
    default:
      return null;
  }
};
const query = reactive({
  address: "",
  testNo: "",
  pageIndex: 1,
  pageSize: 10,
});
const queryTcp = reactive({
  pageNumber: 1,
  pageSize: 10,
  total: 0,
  deviceNo: null,
  passNo: "0",
  measurementStartTime: null,
  measurementEndTime: null,
  time: null,
});
const queryCharts = reactive({
  endDate: null,
  passNo: "0",
  startDate: null,
  deviceNo: null,
  time: null,
});
const options = [
  {
    value: "1",
    label: "通道1",
  },
  {
    value: "2",
    label: "通道2",
  },
  {
    value: "3",
    label: "通道3",
  },
  {
    value: "0",
    label: "全部通道",
  },
];
const tableData = ref<TableItem[]>([]);
const TcpData = ref<TableItem[]>([]);
const pageTotal = ref(0);
// 获取表格数据
const getData = () => {
  getOnlneList({
    testNo: query.testNo,
    pageNumber: query.pageIndex,
    pageSize: query.pageSize,
    sortOrder: "asc",
  }).then((res: any) => {
    tableData.value = res.rows;
    pageTotal.value = res.total || 0;
  });
};
getData();

const getTcp = () => {
  let tiem1 = null;
  let tiem2 = null;
  if (queryTcp.time) {
    tiem1 = changeTime(queryTcp.time[0]);
    tiem2 = changeTime(queryTcp.time[1]);
  }
  // TcpList({
  //   pageNumber: queryTcp.pageNumber,
  //   pageSize: queryTcp.pageSize,
  //   deviceNo: queryTcp.deviceNo,
  //   passNo: queryTcp.passNo,
  //   startTime: tiem1,
  //   endTime: tiem2
  // }).then((res: any)=>{
  // 	TcpData.value = res.rows;
  // 	queryTcp.total = res.total;
  // })
};
getTcp();
// 查询操作
const reset = () => {
  query.pageIndex = 1;
  query.testNo = "";
  getData();
};
const handleSearch = () => {
  query.pageIndex = 1;
  getData();
};
// 分页导航
const handlePageChange = (val: number) => {
  query.pageIndex = val;
  getData();
};
// Tpc列表分页
const changeTpcList = (val: number) => {
  queryTcp.pageNumber = val;
  getTcp();
};
const Tpcreset = () => {
  queryTcp.pageNumber = 1;
  queryTcp.pageSize = 10;
  queryTcp.deviceNo = null;
  queryTcp.passNo = "0";
  queryTcp.time = null;
  getTcp();
};
const chartVisible = ref(false);
const tipBoolen = ref(false);
// Tpc折线图
const getTcpChart = (val: any) => {
  let tiem1 = null;
  let tiem2 = null;
  if (queryCharts.time) {
    tiem1 = changeTime(queryCharts.time[0]);
    tiem2 = changeTime(queryCharts.time[1]);
  }
  if (val.deviceNo) {
    queryCharts.deviceNo = val.deviceNo;
  }
  chartVisible.value = true;
  TcpChart({
    deviceNo: queryCharts.deviceNo,
    endDate: tiem2,
    passNo: queryCharts.passNo,
    startDate: tiem1,
  }).then((val: any) => {
    const arr: any = [0];
    const titel: any = [""];
    console.log(val);
    tipBoolen.value = Boolean(val.rows.length);
    console.log(Boolean(val.rows.length));

    val.rows.forEach((item: any) => {
      arr.push(item.total);
      titel.push(item.dataTime);
    });
    initChart(arr, titel);
  });
};
// 重置折现图
const chartReset = () => {
  (queryCharts.time = null),
    (queryCharts.passNo = "0"),
    getTcpChart(queryCharts);
};
// 处理时间
const changeTime = (val: any) => {
  let time;
  const date = new Date(val);
  time =
    date.getFullYear() +
    "-" +
    (date.getMonth() + 1) +
    "-" +
    date.getDate() +
    " 00:00";
  return time;
};
// 删除操作
const handleDelete = (row: any) => {
  // 二次确认删除
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      const res: any = await deleteDevice({ id: row.id });
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getData();
      } else {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};

// 表格编辑时弹窗和保存
const editVisible = ref(false);
let form = reactive({
  name: "",
  address: "",
  deviceNo: "",
  electricNo: "",
  id: "",
  passNo: "",
  testNo: "",
});
const visibleType = ref("add");
const handleEdit = async (type: string, row: any) => {
  visibleType.value = type;
  editVisible.value = true;
  const res: any = await getDevice({ id: row.id });
  if (res.code === 200) {
    form.deviceNo = res.rows.deviceNo || "";
    form.electricNo = res.rows.electricNo || "";
    form.id = res.rows.id || "";
    form.passNo = res.rows.passNo || "";
    form.testNo = res.rows.testNo || "";
  } else {
    ElMessage.error("获取详情信息失败！");
  }
};

// 新增
const add = () => {
  visibleType.value = "add";
  editVisible.value = true;
  form.deviceNo = "";
  form.electricNo = "";
  form.id = "";
  form.passNo = "";
  form.testNo = "";
};

// 保存新增
const saveEdit = async () => {
  let res: any = null;
  if (visibleType.value === "edit") {
    res = await editDevice({
      deviceNo: form.deviceNo,
      electricNo: [form.electricNo],
      passNo: form.passNo,
      testNo: form.testNo,
      id: form.id,
    });
  } else {
    res = await createDevice({
      deviceNo: form.deviceNo,
      electricNo: [form.electricNo],
      passNo: form.passNo,
      testNo: form.testNo,
    });
  }

  if (res.code === 200) {
    editVisible.value = false;
    ElMessage.success("保存成功！");
    getData();
  } else {
    ElMessage.error("保存失败！");
  }
};
const listVisible = ref(false);
const showModal = () => {
  listVisible.value = true;
};
</script>
<style scoped lang="less">
@import "./index.less";
</style>
